#!/usr/bin/env python3
"""
系统配置文件
"""

import os
from pathlib import Path

class Config:
    """系统配置类"""
    
    # 基础配置
    APP_NAME = "Qwen2.5-VL 视频分析系统"
    APP_VERSION = "1.0.0"
    APP_DESCRIPTION = "基于Qwen2.5-VL多模态大模型的智能视频目标检测系统"
    
    # 服务配置
    HOST = os.getenv("HOST", "0.0.0.0")
    PORT = int(os.getenv("PORT", 8000))
    DEBUG = os.getenv("DEBUG", "false").lower() == "true"
    
    # 模型配置
    MODEL_CLIENT_TYPE = os.getenv("MODEL_CLIENT_TYPE", "vllm")  # vllm, ollama, openai, azure, alibaba
    MODEL_BASE_URL = os.getenv("MODEL_BASE_URL", "http://localhost:8001/v1")
    MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-VL-7B-Instruct")
    MODEL_API_KEY = os.getenv("MODEL_API_KEY", "test")
    MAX_TOKENS = int(os.getenv("MAX_TOKENS", 1024))

    # 不同服务的默认配置
    MODEL_CONFIGS = {
        "vllm": {
            "base_url": "http://localhost:8001/v1",
            "model_name": "Qwen/Qwen2.5-VL-7B-Instruct",
            "api_key": "test"
        },
        "ollama": {
            "base_url": "http://localhost:11434",
            "model_name": "qwen2-vl",
            "api_key": ""
        },
        "openai": {
            "base_url": "https://api.openai.com/v1",
            "model_name": "gpt-4-vision-preview",
            "api_key": ""  # 需要设置环境变量
        },
        "azure": {
            "base_url": "",  # 需要设置Azure endpoint
            "model_name": "gpt-4-vision",
            "api_key": ""  # 需要设置Azure API key
        },
        "alibaba": {
            "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
            "model_name": "qwen-vl-plus",
            "api_key": ""  # 需要设置阿里云API key
        }
    }
    
    # 文件配置
    UPLOAD_DIR = Path(os.getenv("UPLOAD_DIR", "uploads"))
    FRAMES_DIR = Path(os.getenv("FRAMES_DIR", "frames"))
    MAX_FILE_SIZE = int(os.getenv("MAX_FILE_SIZE", 500 * 1024 * 1024))  # 500MB
    
    # 支持的视频格式
    SUPPORTED_VIDEO_FORMATS = {".mp4", ".avi", ".mov", ".mkv", ".wmv", ".flv", ".webm"}
    
    # 视频处理配置
    DEFAULT_FPS_SAMPLING = int(os.getenv("DEFAULT_FPS_SAMPLING", 1))  # 每秒采样帧数
    FRAME_QUALITY = int(os.getenv("FRAME_QUALITY", 100))  # JPEG质量
    CONSECUTIVE_DETECTION_THRESHOLD = int(os.getenv("CONSECUTIVE_DETECTION_THRESHOLD", 2))
    CONFIDENCE_THRESHOLD = float(os.getenv("CONFIDENCE_THRESHOLD", 0.7))
    
    # 图像预处理配置
    ENABLE_IMAGE_ENHANCEMENT = os.getenv("ENABLE_IMAGE_ENHANCEMENT", "true").lower() == "true"
    CLAHE_CLIP_LIMIT = float(os.getenv("CLAHE_CLIP_LIMIT", 2.0))
    CLAHE_TILE_GRID_SIZE = (8, 8)
    
    # 日志配置
    LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
    LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    
    # CORS配置
    CORS_ORIGINS = os.getenv("CORS_ORIGINS", "*").split(",")
    
    # 安全配置
    ENABLE_FILE_VALIDATION = os.getenv("ENABLE_FILE_VALIDATION", "true").lower() == "true"
    MAX_CONCURRENT_TASKS = int(os.getenv("MAX_CONCURRENT_TASKS", 3))
    
    @classmethod
    def create_directories(cls):
        """创建必要的目录"""
        cls.UPLOAD_DIR.mkdir(exist_ok=True)
        cls.FRAMES_DIR.mkdir(exist_ok=True)
    
    @classmethod
    def get_model_config(cls):
        """获取模型配置"""
        # 获取默认配置
        default_config = cls.MODEL_CONFIGS.get(cls.MODEL_CLIENT_TYPE, {})

        # 环境变量覆盖默认配置
        return {
            "client_type": cls.MODEL_CLIENT_TYPE,
            "base_url": cls.MODEL_BASE_URL or default_config.get("base_url"),
            "api_key": cls.MODEL_API_KEY or default_config.get("api_key"),
            "model_name": cls.MODEL_NAME or default_config.get("model_name"),
            "max_tokens": cls.MAX_TOKENS,
            "provider": cls.MODEL_CLIENT_TYPE
        }
    
    @classmethod
    def get_video_config(cls):
        """获取视频处理配置"""
        return {
            "fps_sampling": cls.DEFAULT_FPS_SAMPLING,
            "frame_quality": cls.FRAME_QUALITY,
            "consecutive_threshold": cls.CONSECUTIVE_DETECTION_THRESHOLD,
            "confidence_threshold": cls.CONFIDENCE_THRESHOLD,
            "supported_formats": cls.SUPPORTED_VIDEO_FORMATS,
            "max_file_size": cls.MAX_FILE_SIZE
        }
    
    @classmethod
    def get_image_config(cls):
        """获取图像处理配置"""
        return {
            "enable_enhancement": cls.ENABLE_IMAGE_ENHANCEMENT,
            "clahe_clip_limit": cls.CLAHE_CLIP_LIMIT,
            "clahe_tile_grid_size": cls.CLAHE_TILE_GRID_SIZE
        }
    
    @classmethod
    def validate_config(cls):
        """验证配置"""
        errors = []
        
        # 检查必要的目录
        try:
            cls.create_directories()
        except Exception as e:
            errors.append(f"无法创建目录: {str(e)}")
        
        # 检查端口范围
        if not (1 <= cls.PORT <= 65535):
            errors.append(f"端口号无效: {cls.PORT}")
        
        # 检查文件大小限制
        if cls.MAX_FILE_SIZE <= 0:
            errors.append(f"文件大小限制无效: {cls.MAX_FILE_SIZE}")
        
        # 检查置信度阈值
        if not (0 <= cls.CONFIDENCE_THRESHOLD <= 1):
            errors.append(f"置信度阈值无效: {cls.CONFIDENCE_THRESHOLD}")
        
        return errors

# 开发环境配置
class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    LOG_LEVEL = "DEBUG"

# 生产环境配置
class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    LOG_LEVEL = "WARNING"
    ENABLE_FILE_VALIDATION = True

# 测试环境配置
class TestingConfig(Config):
    """测试环境配置"""
    DEBUG = True
    LOG_LEVEL = "DEBUG"
    MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB for testing
    UPLOAD_DIR = Path("test_uploads")
    FRAMES_DIR = Path("test_frames")

# 根据环境变量选择配置
def get_config():
    """根据环境变量获取配置"""
    env = os.getenv("ENVIRONMENT", "development").lower()
    
    if env == "production":
        return ProductionConfig
    elif env == "testing":
        return TestingConfig
    else:
        return DevelopmentConfig

# 默认配置
config = get_config()

if __name__ == "__main__":
    print(f"当前配置: {config.__name__}")
    print(f"应用名称: {config.APP_NAME}")
    print(f"版本: {config.APP_VERSION}")
    print(f"主机: {config.HOST}:{config.PORT}")
    print(f"模型服务: {config.MODEL_BASE_URL}")
    print(f"调试模式: {config.DEBUG}")
    
    # 验证配置
    errors = config.validate_config()
    if errors:
        print("\n配置错误:")
        for error in errors:
            print(f"  - {error}")
    else:
        print("\n✅ 配置验证通过")
